<?php

namespace App\Listeners;

use App\Common\Func;
use App\Events\AddResourceEvent;
use App\Models\ResourceModel;
use Illuminate\Support\Facades\DB;

class AddResourceListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     * @param AddResourceEvent $event
     * @return array|false
     */
    public function handle(AddResourceEvent $event)
    {
        $params = $event->params;
        try {
            DB::beginTransaction();

            $ids = [];
            $builder = ResourceModel::query();
            foreach ($params as $data) {
                $builderRes = ResourceModel::getIdAndValueAndType($data['value'], $data['type']);
                if ($builderRes) {
                    $id = $builderRes['id'];
                } else {
                    $id = $builder->insertGetId($data);
                }
                $ids[] = $id;
            }
            DB::commit();
            return Func::response('0', '', $ids);
        } catch (\Exception $e) {
            DB::rollBack();
            Func::logError($data, $e->getMessage());
            return Func::response('1');
        }
    }

}
